package org.firebug.spring.boot.war.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.springframework.http.HttpHeaders.*;
import static org.springframework.http.HttpHeaders.USER_AGENT;
import static org.springframework.http.MediaType.*;

@RestController
@RequestMapping(value = "/file")
public class FileController {
    private String dir = "d:/tmp/";

    @RequestMapping(value = "/submit", method = {RequestMethod.POST})
    public ResponseEntity<Map> submit(String username, String password) {
        Map<String, String> user = new HashMap<>();
        user.put("username", username);
        user.put("password", password);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    public ResponseEntity<Map> upload(String username, String password, MultipartFile[] images, MultipartFile desc) throws IOException {
        List<String> files = Arrays.stream(images).map(img -> img.getOriginalFilename()).collect(Collectors.toList());
        Map<String, Object> user = new HashMap<>();
        user.put("username", username);
        user.put("password", password);
        user.put("images", files);
        user.put("desc", desc.getOriginalFilename());
        for(MultipartFile image : images){
            String filename = image.getOriginalFilename();
            FileCopyUtils.copy(image.getInputStream(), new FileOutputStream(new File(dir, filename)));
        }
        String filename = desc.getOriginalFilename();
        FileCopyUtils.copy(desc.getInputStream(), new FileOutputStream(new File(dir, filename)));
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    /* 小文件下载 */
    @RequestMapping(value = "/download/{filename:.+}", method = {RequestMethod.GET})
    public ResponseEntity<byte[]> download(@RequestHeader(value = USER_AGENT) String userAgent, @PathVariable String filename) throws IOException {
        byte[] body = FileCopyUtils.copyToByteArray(new FileInputStream(dir + filename));
        HttpHeaders headers = new HttpHeaders();
        headers.add(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE);
        headers.add(CONTENT_DISPOSITION, "attachment;filename=" + encoding(userAgent, filename));
        return new ResponseEntity<>(body, headers, HttpStatus.OK);
    }

    /* 大文件下载 */
//    @RequestMapping(value = "/download/{filename:.+}", method = {RequestMethod.GET})
//    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable String filename) throws IOException {
//        response.setContentType(APPLICATION_OCTET_STREAM_VALUE);
//        response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" + encoding(request.getHeader(USER_AGENT), filename));
//        InputStream in = new FileInputStream(dir + filename);
//        OutputStream out = response.getOutputStream();
//        FileCopyUtils.copy(in, out);
//    }

    private String encoding(String userAgent, String filename) throws UnsupportedEncodingException {
        if (userAgent.indexOf("MSIE") == -1) {
            return new String(filename.getBytes("UTF-8"), "ISO8859-1");//firefox, opera, chrome等
        } else {
            return URLEncoder.encode(filename, "UTF-8"); //IE
        }
    }
}